
/**
 * 放雪人兄弟音乐
 */
class Tracker {
  constructor(params, audioEnable = true) {
    this.audioEnable = audioEnable;
    this.path = params.assetPath('show/bg.m4a');
    this.isPlaying = false;
  }

  initAudio() {
    if (this.myAudio != null) {
      return this.myAudio;
    }
    const myAudio = this.myAudio = new Audio();
    myAudio.preload = false;
    myAudio.controls = true; // 是否显示隐藏按钮
    myAudio.hidden = true;
    myAudio.src = this.path;
    //绑定音乐结束事件，当音乐播放完成后，将会触发playEndedHandler方法
    //myAudio.addEventListener("ended", playEndedHandler, false);
    document.getElementById("main").appendChild(myAudio);

    //将循环播放关闭，如果开启，将不能触发playEndedHandler方法，只能进行单曲循环
    myAudio.volume = 0.5;
    myAudio.loop = true;
    return myAudio;
  }

  setEnable(audioEnable) {
    if (this.audioEnable === audioEnable) {
      return;
    }
    this.audioEnable = audioEnable;

    if (this.isPlaying ) {
      const myAudio = this.initAudio();
      if (this.audioEnable) {
        myAudio.currentTime = 0;
        try {
          myAudio.play();
        } catch (e) {
          console.error(e);
          this.myAudio = null;
        }
      } else {
        myAudio.pause();
      }
    }
  }

  play() {
    const myAudio = this.initAudio();

    if (!this.isPlaying) {
      // 重置播放位置到开头
      myAudio.currentTime = 0;
      this.isPlaying = true;
    }

    if (!this.audioEnable) {
      return;
    }

    //播放当前音乐
    try {
      myAudio.play();
    } catch (e) {
      console.error(e);
      this.myAudio = null;
    }
  }

  pause() {
    const { myAudio } = this;
    myAudio.pause();
    this.isPlaying = false;
  }
}

export default Tracker;
